package hongniang

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"shangyuapi/data_source"
	"shangyuapi/models"
	"strings"
	"time"
)

type PhonecodeBody struct {
	Phone string `json:"phone" from:"phone"`
}

func Phonecode(ctx *gin.Context) {
	request := PhonecodeBody{}
	ctx.ShouldBind(&request)
	phone := request.Phone
	phone = strings.Replace(phone, " ", "", -1)
	rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
	vcode := fmt.Sprintf("%06v", rnd.Int31n(1000000))

	par, _ := json.Marshal(map[string]interface{}{
		"code": vcode,
	})
	_, err := SendSms("LTAI5tM927iuiTCZtmN8ghrs", "5r2WLYbyqbfX1boMZsrVzPZOpzjbnj", " 闪遇", phone, "SMS_465314147", string(par))
	fmt.Println(err)
	if err == nil {
		phonecode := models.Phonecode{
			Phone:   phone,
			Code:    vcode,
			Enttime: time.Now().Unix() + 900,
		}
		data_source.Db.Create(&phonecode)
	} else {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     err,
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
